package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.domain.OrderInfo;
import com.spzx.domain.OrderItem;
import com.spzx.domain.OrderLog;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.vo.OrderForm;
import com.spzx.vo.R;
import com.spzx.vo.SkuLockVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单Service业务层处理
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RemoteProductService remoteProductService;


    //生成订单接口
    @Override
    public Long submitOrder(OrderForm orderForm) {
        //1 防止订单重复提交
//        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
//                "then\n" +
//                "    return redis.call(\"del\",KEYS[1])\n" +
//                "else\n" +
//                "    return 0\n" +
//                "end";
//
//        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
//        redisScript.setScriptText(scriptText);
//        redisScript.setResultType(Long.class);
//        Long flag = (Long) redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), orderForm.getTradeNo());
//        if (flag == 0) {
//            throw new ServiceException("请勿重复提交订单，请尝试重试");
//        }
//
//        //2 判断结算订单项不能为空
//
//        List<OrderItem> orderItemList = orderForm.getOrderItemList();
//        if (CollectionUtils.isEmpty(orderItemList)){
//            throw new ServiceException("提交订单商品为空!");
//        }
//
//        //3 校验价格
//
//        //3.1 orderItemList获取所有skuId集合
//        List<Long> skuIdList =
//                orderItemList.stream().map(OrderItem::getSkuId).collect(Collectors.toList());
//
//
//        //3.3 把查询sku的最新价格集合转换map集合，map的key skuId，value价格
//        Map<Long, BigDecimal> map =
//                skuPriceList.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
//        //3.4 比较orderItemList价格和最新价格是否相同，如果不相同，价格变化
//        String priceCheckResult = "";
//
//        for (OrderItem orderItem : orderItemList) {
//
//            if (orderItem.getSkuPrice().compareTo(map.get(orderItem.getSkuId())) != 0) {
//                priceCheckResult += orderItem.getSkuName() + "价格变化了; ";
//            }
//        }
//        //3.5 如果价格变化，远程调用更新购物车商品价格
//        if (StringUtils.isNotEmpty(priceCheckResult)){
//            //远程调用，更新购物车价格
//            throw new ServiceException(priceCheckResult);
//        }
//
//        //4 校验库存并锁定库存
//
//        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
//            SkuLockVo skuLockVo = new SkuLockVo();
//            skuLockVo.setSkuId(orderItem.getSkuId());
//            skuLockVo.setSkuNum(orderItem.getSkuNum());
//            return skuLockVo;
//        }).collect(Collectors.toList());
//
//        //5 生成订单（订单表添加数据order_info  和  order_item）
//
//        Long orderId = this.saveOrder(orderForm);
//        //6 删除购物车选中商品
//
//        //TODO 7 发送延迟消息，实现30分钟没有支付订单，解锁库存
//
//        //TODO 8 下单失败，解锁库存
//
//        //9 返回订单id
        return 1L;
    }

    private Long saveOrder(OrderForm orderForm) {
        // 获取当前登录用户的id

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setRemark(orderForm.getRemark());

        //计算总价格
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            BigDecimal skuPrice = orderItem.getSkuPrice();
            Integer skuNum = orderItem.getSkuNum();
            totalAmount = totalAmount.add(skuPrice.multiply(new BigDecimal(skuNum)));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0);
        baseMapper.insert(orderInfo);

        //保存订单明细
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        return orderInfo.getId();
    }

}
